package cn.hubujyjs.lp.config;

import cn.hubujyjs.lp.utils.R;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.判断是否需要进行拦截(依据ThreadLocal中是否有用户)
        if (UserHolder.getUser()==null && AdminHolder.getUser()==null){
//            response.setStatus(401);
            String result = JSONUtil.toJsonStr(R.fail("请登录").code(401));
            PrintWriter printWriter=null;
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json");
            printWriter=response.getWriter();
            printWriter.print(result);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        /*
          渲染视图后
         */
        UserHolder.removeUser();
    }
}
